module lab3 (
    input clk,
    input rst,
    input [3:0] key_row,
    input [3:0] k,
    output [3:0] key_col,
    output [7:0] seg,
    output [2:0] sel
);

  wire [3:0] val;
  key u_key (
      clk,
      rst,
      key_row,
      key_col,
      val
  );

  wire [7:0] x;
  wire [7:0] y;
  wire [15:0] res;
  reg [31:0] data;
  reg [15:0] prev_data;
  reg [3:0] prev_val;
  reg en;
  reg en_v;

  mult u_mult (
      clk,
      rst,
      en,
      x,
      y,
      res
  );

  assign x = data[31:24];
  assign y = data[23:16];

  always @(posedge clk or negedge rst) begin
    if (!rst) begin
      data <= 32'd0;
    end else if (en_v) begin
      if (k[0]) begin
        data[31:28] <= val;
      end else if (k[1]) begin
        data[27:24] <= val;
      end else if (k[2]) begin
        data[23:20] <= val;
      end else if (k[3]) begin
        data[19:16] <= val;
      end
      data[15:0] <= res;
    end else begin
      data[15:0] <= res;
    end
  end

  always @(posedge clk or negedge rst) begin
    if (!rst) begin
      en_v <= 1'b0;
      prev_val <= 4'd0;
    end else if (prev_val != val) begin
      en_v <= 1'b1;
      prev_val <= val;
    end else begin
      en_v <= 1'b0;
      prev_val <= prev_val;
    end
  end

  always @(posedge clk or negedge rst) begin
    if (!rst) begin
      en <= 1'b0;
      prev_data <= 16'd0;
    end else if (prev_data != data[31:16]) begin
      en <= 1'b1;
      prev_data <= data[31:16];
    end else begin
      en <= 1'b0;
      prev_data <= prev_data;
    end
  end

  display u_display (
      clk,
      rst,
      data,
      seg,
      sel
  );

endmodule
